package com.leadbank.bigdata.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
import org.springframework.data.hadoop.hbase.RowMapper;

import java.io.IOException;

/**
 * Created by hp on 2018/5/23.
 */
public class HBaseTest {

    private static final String TABLE_NAME = "scores";
    private static final String ROW_KEY = "Tom";
    private static final String COLUMN_FAMILY = "course";
    private static final String QUALIFIER = "art";
    private static ApplicationContext applicationContext;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("做一些前提条件的设置");
        // 加载Spring配置文件
        applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("释放一些资源");
    }


    @Test
    public void test() {

        // 获取HbaseTemplate
        HbaseTemplate hbaseTemplate = (HbaseTemplate) applicationContext.getBean("hbaseTemplate");
        // 通过表名和rowKey获取最近一行数据
        String result = hbaseTemplate.get(TABLE_NAME, ROW_KEY, new RowMapper<String>() {
            public String mapRow(Result result, int rowNum) throws Exception {
                return Bytes.toString(result.getValue(COLUMN_FAMILY.getBytes(), QUALIFIER.getBytes()));
            }
        });
        System.out.println(result); // 输出结果是：value1
    }

    @Test
    public void test2() throws IOException {
        // 获取HbaseTemplate
        Configuration hBaseConfiguration = (Configuration) applicationContext.getBean("hbaseConfiguration");
        HBaseAdmin hBaseAdmin = new HBaseAdmin(hBaseConfiguration);

        if (hBaseAdmin.tableExists(TABLE_NAME)) {
            System.out.println("table Exists!");
        } else {
            System.out.println("table not Exists!");
        }




    }
}
